<template>
    <div class="addAirPlan">
        <custom-dialog :title="title" size="smallLarge" @dialogClose="dialogClose">
            <div class="topStep">
                <Tabs :value="current" style="margin: 0">
                    <TabPane label="基本方案" name="基本方案" :disabled="current == '时间方案'">
                        <div class="bottomContent">
                            <div class="famc">
                                <label><span style="color: red">*</span> 方案名称：</label>
                                <Input v-model="SCHE_NAME" placeholder="请输入方案名称" style="width: 300px" />
                            </div>
                            <div class="settings">
                                <div class="workMode">
                                    <label class="leftLabel">工作模式</label>
                                    <div>
                                        <CheckboxGroup v-model="workMode">
                                            <Checkbox label="调温"></Checkbox>
                                            <Checkbox label="人感"></Checkbox>
                                            <Checkbox label="温度"></Checkbox>
                                            <Checkbox label="时间"></Checkbox>
                                            <Checkbox label="手动"></Checkbox>
                                            <Checkbox label="计量"></Checkbox>
                                            <Checkbox label="断电"></Checkbox>
                                            <Checkbox label="机房省电"></Checkbox>
                                            <Checkbox label="定时"></Checkbox>
                                        </CheckboxGroup>
                                    </div>
                                </div>
                                <div class="work">
                                    <div class="item">
                                        <label class="leftLabel"> 制冷开启温度 </label>
                                        <InputNumber :max="99" :min="0" v-model="value1"></InputNumber>
                                        ℃
                                    </div>
                                    <div class="item">
                                        <label class="leftLabel"> 制冷关机温度 </label>
                                        <InputNumber :max="99" :min="0" v-model="value2"></InputNumber>
                                        ℃
                                    </div>
                                    <div class="item">
                                        <label class="leftLabel"> 制冷开机温度 </label>
                                        <InputNumber :max="99" :min="0" v-model="value3"></InputNumber>
                                        ℃
                                    </div>
                                </div>
                                <div class="work">
                                    <div class="item">
                                        <label class="leftLabel"> 制热开启温度 </label>
                                        <InputNumber :max="99" :min="0" v-model="value4"></InputNumber>
                                        ℃
                                    </div>
                                    <div class="item">
                                        <label class="leftLabel"> 制热关机温度 </label>
                                        <InputNumber :max="99" :min="0" v-model="value5"></InputNumber>
                                        ℃
                                    </div>
                                    <div class="item">
                                        <label class="leftLabel"> 制热开机温度 </label>
                                        <InputNumber :max="99" :min="0" v-model="value6"></InputNumber>
                                        ℃
                                    </div>
                                </div>
                                <div class="work">
                                    <div class="item">
                                        <label class="leftLabel"> 夏季判断温度 </label>
                                        <InputNumber :max="31" :min="20" v-model="value7"></InputNumber>
                                        ℃
                                    </div>
                                    <div class="item">
                                        <label class="leftLabel"> 冬季判断温度 </label>
                                        <InputNumber :max="20" :min="0" v-model="value8"></InputNumber>
                                        ℃
                                    </div>
                                </div>
                                <div class="work">
                                    <div class="item">
                                        <label class="leftLabel"> 制冷目标温度 </label>
                                        <InputNumber :max="99" :min="0" v-model="value9"></InputNumber>
                                        ℃
                                    </div>
                                    <div class="item">
                                        <label class="leftLabel"> 制热目标温度 </label>
                                        <InputNumber :max="99" :min="0" v-model="value10"></InputNumber>
                                        ℃
                                    </div>
                                </div>
                                <div class="work">
                                    <div class="item">
                                        <label class="leftLabel"> 开启温度使能 </label>
                                        <Select v-model="wdsnkq" style="width: 100px">
                                            <Option v-for="item in wdsnkqList" :value="item.value" :key="item.value">{{
                                                item.label
                                            }}</Option>
                                        </Select>
                                    </div>
                                    <div class="item">
                                        <label class="leftLabel"> 使能运行方式 </label>
                                        <Select v-model="snyxfs" style="width: 120px">
                                            <Option v-for="item in snyxfsList" :value="item.value" :key="item.value">{{
                                                item.label
                                            }}</Option>
                                        </Select>
                                    </div>
                                    <div class="item">
                                        <label class="leftLabel"> 开关机控制 </label>
                                        <Select v-model="kgjkz" style="width: 140px">
                                            <Option v-for="item in kgjkzList" :value="item.value" :key="item.value">{{
                                                item.label
                                            }}</Option>
                                        </Select>
                                    </div>
                                </div>
                                <div class="work">
                                    <div class="item">
                                        <label class="leftLabel"> 人感人数 </label>
                                        <InputNumber :max="50000" :min="1" v-model="value11"></InputNumber>
                                        人
                                    </div>
                                    <div class="item">
                                        <label class="leftLabel"> 人感延时（s） </label>
                                        <InputNumber :max="5000" :min="1" v-model="value12"></InputNumber>
                                        秒
                                    </div>
                                    <div class="item">
                                        <label class="leftLabel"> 临时设定时间 </label>
                                        <InputNumber :max="255" :min="0" v-model="value13"></InputNumber>
                                        分
                                    </div>
                                </div>
                            </div>
                        </div></TabPane
                    >
                    <TabPane label="时间方案" name="时间方案" :disabled="current == '基本方案'">
                        <div class="bottomContent">
                            <div class="settings">
                                <div class="timeSet" v-for="(item, index) in timeSchemeList" :key="index">
                                    <label>{{ item.day }}开启时间：</label>
                                    <span>
                                        <Checkbox v-model="item.checked"></Checkbox>
                                        人感
                                    </span>
                                    <TimePicker
                                        format="HH:mm"
                                        placeholder=""
                                        style="width: 80px"
                                        size="small"
                                        v-model="item.time1"
                                    ></TimePicker>
                                    ~
                                    <TimePicker
                                        format="HH:mm"
                                        placeholder=""
                                        style="width: 80px"
                                        size="small"
                                        v-model="item.time2"
                                    ></TimePicker>

                                    <img src="@/assets/images/airIndex/plus.png" @click="plusItem(item, index)" />
                                    <img src="@/assets/images/airIndex/reduce.png" @click="reduceItem(item, index)" />
                                </div>
                            </div></div
                    ></TabPane>
                </Tabs>
            </div>
            <div style="text-align: right">
                <el-button type="primary" class="nextBtn" style="margin-left: 10px" v-if="isFirst" @click="dqClick" :loading="showloading"
                    >读取</el-button
                >
                <el-button type="primary" class="nextBtn" @click="current = '基本方案'" v-if="current == '时间方案'">上一步</el-button>
                <el-button type="primary" class="nextBtn" @click="nextStep" v-if="current == '基本方案'">下一步</el-button>
                <el-button type="primary" class="nextBtn" @click="finish" v-if="current == '时间方案' && !isFirst" style="margin-left: 10px"
                    >完成</el-button
                >
            </div>
        </custom-dialog>
        <loading title="数据处理中，请稍等..." :show="showloading"></loading>
    </div>
</template>

<script>
import customDialog from '@/components/customComponents/customDialog'
import {PopupCommon} from '@/libs/popupCommon'
import {Utility} from '@/libs/utility'
import {checkTimeSegments} from '@/libs/timeUtils'
import {AjaxCommon} from '@/libs/apiCommon'
import loading from '@/components/loading'
export default {
    name: 'addAirPlan',
    props: ['title', 'wkfaId', 'isFirst', 'deviceInfo'],
    components: {customDialog, loading},
    data() {
        return {
            showloading: false,
            LIST_GUID: '',
            /** 方案名称 */
            SCHE_NAME: '',
            dayList: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
            timeSchemeList: [
                {
                    day: '周一',
                    checked: false,
                    time1: '',
                    time2: ''
                },
                {
                    day: '周二',
                    checked: false,
                    time1: '',
                    time2: ''
                },
                {
                    day: '周三',
                    checked: false,
                    time1: '',
                    time2: ''
                },
                {
                    day: '周四',
                    checked: false,
                    time1: '',
                    time2: ''
                },
                {
                    day: '周五',
                    checked: false,
                    time1: '',
                    time2: ''
                },
                {
                    day: '周六',
                    checked: false,
                    time1: '',
                    time2: ''
                },
                {
                    day: '周日',
                    checked: false,
                    time1: '',
                    time2: ''
                }
            ],
            wdsnkq: 1,
            /// 温度模式开启温度使能   0,关闭；01，开启，控制器默认值为1；不设置传255
            wdsnkqList: [
                {
                    label: '开启',
                    value: 1
                },
                {
                    label: '关闭',
                    value: 0
                }
            ],
            snyxfs: 1,
            // 温度使能运行方式 1,按天使能；2，按时段使能控制器默认值为1；不设置传255
            snyxfsList: [
                {
                    label: '按天使能',
                    value: 1
                },
                {
                    label: '按时段使能',
                    value: 2
                }
            ],
            kgjkz: 2,
            // 温度模式开关机控制1,制冷/制热开机控制；2，制冷/制热关机控制；3，制冷/制热开关机控制；默认为2;不设置传255
            kgjkzList: [
                {
                    label: '制冷/制热关机',
                    value: 2
                },
                {
                    label: '制冷/制热开机',
                    value: 1
                },
                {
                    label: '制冷/制热开关机',
                    value: 3
                }
            ],
            workMode: ['手动'],
            current: '基本方案',
            value1: 26,
            value2: 24,
            value3: 26,
            value4: 18,
            value5: 22,
            value6: 18,
            value7: 33,
            value8: 10,
            value9: 18,
            value10: 26,
            value11: '',
            value12: '',
            value13: 30,
            firstPageData: {}
        }
    },
    computed: {},
    created() {
        this.getDetail()
    },
    methods: {
        async dqClick() {
            const deviceInfo = this.deviceInfo
            this.showloading = true
            // 时段控制
            const data2 = await AjaxCommon(`/api/Eq/GetEqRtBadVal?eqid=${deviceInfo.id}&sjx=10`, 'post', {})
            // Sjx=12 读取策略常规参数
            const data1 = await AjaxCommon(`/api/Eq/GetEqRtBadVal?eqid=${deviceInfo.id}&sjx=12`, 'post', {})
            const OPTIONS = data1.data.Message
            const DAY_SCHE = data2.data.Message
            if (OPTIONS == '' || DAY_SCHE == '') {
                PopupCommon.notify('info', '未读取到数据')
            } else {
                // // 工作模式
                if (OPTIONS) {
                    this.setStepOne(OPTIONS.split('|'))
                }
                if (DAY_SCHE) {
                    this.setStepTwo(DAY_SCHE.split('/'))
                }
            }
            this.showloading = false
        },
        setStepOne(OPTIONS) {
            const self = this
            // 工作模式
            // const OPTIONS = data.OPTIONS.split('|')
            // 获取第一个页面的内容 格式如下（17个参数，通过‘|’分隔）
            // 人感延迟时间
            this.value12 = this.valueShow(OPTIONS[0])
            // 人感人数
            this.value11 = this.valueShow(OPTIONS[1])
            // 制冷开启温度
            this.value1 = this.valueShow(OPTIONS[2])
            // 制热开启温度
            this.value4 = this.valueShow(OPTIONS[3])
            // 制冷开机温度
            this.value3 = this.valueShow(OPTIONS[4])
            // 制热开机温度
            this.value6 = this.valueShow(OPTIONS[5])
            // 制冷关机温度
            this.value2 = this.valueShow(OPTIONS[6])
            // 制热关机温度
            this.value5 = this.valueShow(OPTIONS[7])
            // 临时设定时间
            this.value13 = this.valueShow(OPTIONS[8])
            // 夏季判断温度
            this.value7 = this.valueShow(OPTIONS[9])
            // 冬季判断温度
            this.value8 = this.valueShow(OPTIONS[10])
            // 夏天目标温度值
            this.value10 = this.valueShow(OPTIONS[11])
            // 冬季目标温度值
            this.value9 = this.valueShow(OPTIONS[12])
            // 温度模式开启温度使能
            this.wdsnkq = this.valueShow(OPTIONS[13])
            // 温度使能运行方式
            this.snyxfs = this.valueShow(OPTIONS[14])
            // 温度模式开关机控制
            this.kgjkz = this.valueShow(OPTIONS[15])
            const wmSplit = OPTIONS[16].split('')
            let workMode = []
            if (wmSplit[0] == 1) {
                workMode.push('调温')
            }
            if (wmSplit[1] == 1) {
                workMode.push('人感')
            }
            if (wmSplit[2] == 1) {
                workMode.push('温度')
            }
            if (wmSplit[3] == 1) {
                workMode.push('时间')
            }
            if (wmSplit[4] == 1) {
                workMode.push('手动')
            }
            if (wmSplit[5] == 1) {
                workMode.push('计量')
            }
            if (wmSplit[6] == 1) {
                workMode.push('断电')
            }
            if (wmSplit[7] == 1) {
                workMode.push('机房省电')
            }
            if (wmSplit[8] == 1) {
                workMode.push('定时')
            }
            self.workMode = workMode
        },
        setStepTwo(DAY_SCHE) {
            const self = this
            let timeSchemeList = []
            let dayChinese = ''
            let checked = true
            let time1 = ''
            let time2 = ''
            let daySplit = []
            let dayList = []
            let dayListSplit = []
            DAY_SCHE.forEach((t) => {
                daySplit = t.split('-')
                dayChinese = self.dayList[parseInt(daySplit[0]) - 1]
                dayList = daySplit[1].split('|')
                dayList.forEach((day) => {
                    dayListSplit = day.split(',')
                    checked = dayListSplit[0] == 1
                    time1 = dayListSplit[1].indexOf('FF') != -1 ? '' : dayListSplit[1]
                    time2 = dayListSplit[2].indexOf('FF') != -1 ? '' : dayListSplit[2]
                    timeSchemeList.push({
                        day: dayChinese,
                        checked,
                        time1,
                        time2
                    })
                })
            })
            self.timeSchemeList = timeSchemeList
        },
        async getDetail() {
            const wkfaId = this.wkfaId
            if (wkfaId) {
                this.LIST_GUID = wkfaId
                const wkfaList = await AjaxCommon(`/api/TimePlan/GetAirTimePlan`, 'get', null)
                const list = wkfaList?.data?.Message ?? []
                const data = list?.find((t) => t.LIST_GUID == wkfaId) ?? null
                if (data == null) {
                    return
                }
                const self = this
                self.SCHE_NAME = data.SCHE_NAME
                // 工作模式
                const OPTIONS = data.OPTIONS.split('|')
                self.setStepOne(OPTIONS)

                const DAY_SCHE = data.DAY_SCHE.split('/')
                self.setStepTwo(DAY_SCHE)
            }
        },
        finish() {
            const self = this
            if (this.SCHE_NAME?.trim() == '') {
                PopupCommon.notify('info', '请输入方案名称')
                return
            }

            let timeSchemeList = this.timeSchemeList

            // 不允许出现没有开始或结束时间的情况
            let isTrue = true
            timeSchemeList.forEach((t) => {
                if ((t.time1 == '' && t.time2 != '') || (t.time1 != '' && t.time2 == '')) {
                    isTrue = false
                }
            })

            if (!isTrue) {
                PopupCommon.notify('info', '开始时间和结束时间要么都填写，要么都不填写')
                return
            }
            const timeSchemeListTemp = timeSchemeList.filter((t) => t.time1 != '' && t.time2 != '')
            //  是否存在 start > end 的项
            let hasStartGreaterThanEnd = false
            // 是否存在时间段重叠
            let hasOverlap = false
            // 分组
            const groupData = Utility.arrayGroup(timeSchemeListTemp, (t) => t.day)
            groupData.forEach((t) => {
                const d = checkTimeSegments(t.values, 'time1', 'time2')
                if (d.hasStartGreaterThanEnd) {
                    hasStartGreaterThanEnd = true
                }
                if (d.hasOverlap) {
                    hasOverlap = true
                }
            })
            if (hasStartGreaterThanEnd) {
                PopupCommon.notify('info', '存在开始时间大于结束时间的情况，请重新填写')
                return
            }
            if (hasOverlap) {
                PopupCommon.notify('info', '存在时间段重叠的情况')
                return
            }
            console.log(timeSchemeList)

            const groupData1 = Utility.arrayGroup(timeSchemeList, (t) => t.day)
            let finishValue = ''
            groupData1.forEach((t, i) => {
                let first = i + 1 + '-'
                let firstRg = 0
                t.values.forEach((b, bIndex) => {
                    // 第一个参数为人感是否启用0不启用1为启用，
                    firstRg = b.checked ? 1 : 0
                    if (b.time1 && b.time2) {
                        first += `${firstRg},${b.time1},${b.time2}${bIndex == t.values.length - 1 ? '/' : '|'}`
                    } else {
                        first += `FF,FF:FF,FF:FF${bIndex == t.values.length - 1 ? '/' : '|'}`
                    }
                })
                finishValue += first
            })
            finishValue = finishValue.substring(0, finishValue.length - 1)

            // 获取数据
            const firstPageData = this.firstPageData

            if (this.LIST_GUID) {
                AjaxCommon('/api/TimePlan/EditAirTimePlan', 'post', {
                    LIST_GUID: this.LIST_GUID,
                    SCHE_NAME: this.SCHE_NAME,
                    OPTIONS: firstPageData,
                    DAY_SCHE: finishValue,
                    YEAR_SCHE: ''
                }).then((res) => {
                    if (res?.data?.Code == 200) {
                        PopupCommon.notify('success', '编辑成功')
                        // self.initPage(self.treeList)
                        self.dialogClose(true)
                    } else {
                        const msg = res?.data?.Message
                        if (msg) {
                            PopupCommon.notify('error', msg)
                        }
                    }
                })
            } else {
                AjaxCommon('/api/TimePlan/AddAirTimePlan', 'post', {
                    LIST_GUID: this.LIST_GUID,
                    SCHE_NAME: this.SCHE_NAME,
                    OPTIONS: firstPageData,
                    DAY_SCHE: finishValue,
                    YEAR_SCHE: ''
                }).then((res) => {
                    if (res?.data?.Code == 200) {
                        PopupCommon.notify('success', '新增成功')
                        // self.initPage(self.treeList)
                        self.dialogClose(true)
                    } else {
                        const msg = res?.data?.Message
                        if (msg) {
                            PopupCommon.notify('error', msg)
                        }
                    }
                })
            }
        },
        nextStep() {
            this.current = '时间方案'
            // 获取第一个页面的内容 格式如下（17个参数，通过‘|’分隔）
            // 人感延迟时间 this.value12
            // 人感人数 this.value11
            // 制冷开启温度 this.value1
            // 制热开启温度 this.value4
            // 制冷开机温度 this.value3
            // 制热开机温度 this.value6
            // 制冷关机温度 this.value2
            // 制热关机温度 this.value5
            // 临时设定时间 this.value13
            // 夏季判断温度 this.value7
            // 冬季判断温度 this.value8
            // 夏天目标温度值 this.value10
            // 冬季目标温度值 this.value9
            // 温度模式开启温度使能 this.wdsnkq
            // 温度使能运行方式 this.snyxfs
            // 温度模式开关机控制 this.kgjkz
            //  this.workMode
            const workMode = this.workMode
            let controlValue = ''
            controlValue += workMode.indexOf('调温') != -1 ? 1 : 0
            controlValue += workMode.indexOf('人感') != -1 ? 1 : 0
            controlValue += workMode.indexOf('温度') != -1 ? 1 : 0
            controlValue += workMode.indexOf('时间') != -1 ? 1 : 0
            controlValue += workMode.indexOf('手动') != -1 ? 1 : 0
            controlValue += workMode.indexOf('计量') != -1 ? 1 : 0
            controlValue += workMode.indexOf('断电') != -1 ? 1 : 0
            controlValue += workMode.indexOf('机房省电') != -1 ? 1 : 0
            controlValue += workMode.indexOf('定时') != -1 ? 1 : 0
            const oneValue = `${this.valueEmpty(this.value12)}|${this.valueEmpty(this.value11)}|${this.valueEmpty(
                this.value1
            )}|${this.valueEmpty(this.value4)}|${this.valueEmpty(this.value3)}|${this.valueEmpty(this.value6)}|${this.valueEmpty(
                this.value2
            )}|${this.valueEmpty(this.value5)}|${this.valueEmpty(this.value13)}|${this.valueEmpty(this.value7)}|${this.valueEmpty(
                this.value8
            )}|${this.valueEmpty(this.value10)}|${this.valueEmpty(this.value9)}|${this.valueEmpty(this.wdsnkq)}|${this.valueEmpty(
                this.snyxfs
            )}|${this.valueEmpty(this.kgjkz)}|${controlValue}`
            this.firstPageData = oneValue
            // PopupCommon.notify('info', `第一个页面的值：${oneValue}`)
            console.log(oneValue, oneValue.split('|').length)
            // const stepOneValue = `人感延迟时间 | 人感人数 | 制冷开启温度 | 制热开启温度 | 制冷开机温度 | 制热开机温度 | 制冷关机温度 | 制热关机温度 | 临时设定时间
            //  | 夏季判断温度 | 冬季判断温度 | 夏天目标温度值 | 冬季目标温度值 | 温度模式开启温度使能 | 温度使能运行方式 | 温度模式开关机控制
            //  | 温度模式开关机控制|
            //  (air.ARR.工作状态字.调温 ? 0 : 1) + (air.ARR.工作状态字.人感 ? 0 : 1) +
            //  (air.ARR.工作状态字.温度 ? 0 : 1) (air.ARR.工作状态字.时间 ? 0 : 1) +
            //  (air.ARR.工作状态字.手动 ? 0 : 1) + (air.ARR.工作状态字.计量 ? 0 : 1)(air.ARR.工作状态字.断电 ? 0 : 1) +
            //  (air.ARR.工作状态字.机房省电 ? 0 : 1) + (air.ARR.工作状态字.定时 ? 0 : 1);`
        },
        /** 没有设置值传255 */
        valueEmpty(value) {
            return typeof value == 'string' && value == '' ? 255 : value
        },
        valueShow(value) {
            return value == '255' ? '' : parseInt(value)
        },
        /** 设置值 */
        valueConfig(value, min, max) {
            if (value >= max) {
                return max
            } else if (value <= min) {
                return min
            } else {
                return value
            }
        },
        plusItem(item, index) {
            // 同一个类型的最多8个
            const list = JSON.parse(JSON.stringify(this.timeSchemeList))
            if (list.filter((t) => t.day == item.day)?.length == 8) {
                PopupCommon.notify('info', '同一个时间方案最多创建8个')
                return
            }
            item.time1 = item.time2
            item.time2 = ''
            list.splice(index, 0, item)
            this.timeSchemeList = list
        },
        reduceItem(item, index) {
            const list = JSON.parse(JSON.stringify(this.timeSchemeList))
            if (list.filter((t) => t.day == item.day).length > 1) {
                list.splice(index, 1)
                this.timeSchemeList = list
            } else {
                PopupCommon.notify('info', '同一个时间方案，最少保留一个')
            }
        },
        dialogClose(isSuccess) {
            this.$emit('dialogClose', isSuccess ? isSuccess : '')
        }
    }
}
</script>

<style lang="scss">
.ivu-tabs-bar {
    margin-bottom: 0 !important;
}
.topStep {
    width: 100%;
    // height: 500px;
    overflow: hidden;
}
.bottomContent {
    height: 415px;
    .famc {
        display: flex;
        align-items: center;
        justify-content: flex-start;
    }
    .settings {
        margin-top: 10px;
        border: 1px solid #ddd;
        padding: 10px;
        border-radius: 4px;
        display: flex;
        flex-direction: column;
        max-height: 450px;
        overflow-y: auto;
        .leftLabel {
            width: 100px;
            display: inline-block;
            text-align: left;
        }
        .workMode {
            display: flex;
            width: 100%;
        }
        .work {
            margin-top: 10px;
            display: flex;
            width: 100%;
            gap: 10px;
            .item {
                width: calc((100% - 10px) / 3);
            }
        }
        .timeSet {
            margin-top: 10px;
            display: flex;
            width: 100%;
            gap: 10px;
            justify-content: center;
            align-items: center;
            img {
                width: 16px;
                height: 16px;
                margin-left: 5px;
                cursor: pointer;
            }
        }
    }
    padding: 20px 0;
    .nextBtn {
        float: right;
    }
}
</style>